package com.example.service;

import com.example.entity.Supplier;
import com.example.exception.CustomException;
import com.example.mapper.SupplierMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

@Service
public class SupplierService {

    @Resource
    private SupplierMapper supplierMapper;

    private static final String EMAIL_REGEX = "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$"; // 正则表达式：邮箱
    private static final String PHONE_REGEX = "^\\d{11}$"; // 正则表达式：11位数字

    private boolean isValidEmail(String email) {
        return Pattern.matches(EMAIL_REGEX, email);
    }

    private boolean isValidPhone(String phone) {
        return Pattern.matches(PHONE_REGEX, phone);
    }

    public void add(Supplier supplier) {
        // 校验电话是否为11位
        if (!isValidPhone(supplier.getPhone())) {
            throw new CustomException("电话号码必须是11位数字");
        }

        // 校验邮箱格式
        if (!isValidEmail(supplier.getEmail())) {
            throw new CustomException("邮箱格式不正确");
        }

        supplierMapper.insert(supplier);
    }

    public PageInfo<Supplier> selectPage(Integer pageNum, Integer pageSize, Supplier supplier) {
        PageHelper.startPage(pageNum, pageSize);
        List<Supplier> list = supplierMapper.selectAll(supplier);
        return PageInfo.of(list);
    }

    public void update(Supplier supplier) {
        // 校验电话是否为11位
        if (!isValidPhone(supplier.getPhone())) {
            throw new CustomException("电话号码必须是11位数字");
        }

        // 校验邮箱格式
        if (!isValidEmail(supplier.getEmail())) {
            throw new CustomException("邮箱格式不正确");
        }

        supplierMapper.updateById(supplier);
    }

    public void deleteById(Integer id) {
        supplierMapper.deleteById(id);
    }

    public List<Supplier> selectAll(Supplier supplier) {
        return supplierMapper.selectAll(supplier);
    }
}
